#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2019-11-28 14:42:09
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：


from time_ext import *
import logging

log = logging.getLogger('main.timeExt')


# 时间字符串转utc
def StrToUtc(t):
    s = re.findall("\d+", str(t).strip())
    s = s + ['00', ] if len(s) < 6 else s
    ss = "{}-{:0>2s}-{:0>2s} {:0>2s}:{:0>2s}:{:0>2s}".format(*s)[:19]
    utc = int(time.mktime(time.strptime(ss, '%Y-%m-%d %H:%M:%S')))
    return utc
str_to_utc =StrToUtc

def format_str(string):
    t = re.findall('\d+', string)
    return "{}-{:0>2s}-{:0>2s} {:0>2s}:{:0>2s}:{:0>2s}".format(*t)


# 获取当前时间字段
def get_sql_now_time_field(name):
    name = name.lower()
    if name in ("access", "mysql"):
        return "NOW()"
    if name in ("mssql", "sql server", "sqlserver"):
        return "GETDATE()"
    if name == 'oracle':
        return "SYSDATE"
    if name == "sqlite":
        return "DATETIME(STRFTIME('%s','now'),'unixepoch','localtime')"


def DatetimeToStr(t):
    pass


def DatetimeStrToNumber(t):
    return "".join(re.findall('\d+', t))


datetime_to_number = DatetimeStrToNumber

#获取无符号时间
def get_number_datatime():
    t = get_datetime_str()
    return DatetimeStrToNumber(t)


def NumberToDateTimeStr(t):
    return "{}-{}-{} {}:{}:{}".format(t[:4], t[4:6], t[6:8], t[8:10], t[10:12], t[12:14])


# 字符串转datetime
def str_to_datetime(value):
    if isinstance(value, datetime.datetime):
        return value
    if not value:
        log.warning("时间值:{}不是为空,不能转换时间..".format(value))
        return
    value = value.replace('  ', ' ')
    if value.isdigit() and len(value) == 14:
        value = NumberToDateTimeStr(value)

    data = re.findall('^(\d+).(\d+).(\d+).(\d+).(\d+).(\d+)', value)
    if data and len(data[0]) == 6:
        value = '{:0>4d}-{:0>2d}-{:0>2d} {:0>2d}:{:0>2d}:{:0>2d}'.format(*list(map(int, data[0])))
        return datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
    else:
        log.warning("时间值:{},不是一个标准时间,标准格式如: 2020-11-11 12:12:12".format(value))


# 标准19位时间字符转datetime
def time_str_to_datetime(time_str):
    try:
        return datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
    except:
        return time_str


# utc转字符串
def UtcToStr(t):
    return FormatStr(t)


utc_to_datetime_str = UtcToStr


# Utc转datetime
def UtcToDatetime(t):
    tt = UtcToStr(t)
    return str_to_datetime(tt)


# 格式Utc
def FormatStr(t, fmt = "-", formatStr = None):
    fmt = "%Y{0}%m{0}%d %H:%M:%S".format(fmt)
    if formatStr:
        fmt = "".join(["%{}".format(c) if c in ('Y', 'm', 'd', 'H', 'M', 'S') else c for c in formatStr])
    now = time.strftime(fmt, time.localtime(int(t)))
    return now


# 当前UTC
def GetUtc():
    return int(time.time())


# 当前Datatime
def GetDatetime():
    return UtcToDatetime(time.time())


# 当前时间字符串
def GetDatetimeStr():
    return UtcToStr(time.time())


get_datetime_str = GetDatetimeStr


# 字符转Mysql时间
def StrToMysqlDatetime(t = ""):
    return "STR_TO_DATE({}, '%Y-%m-%d %H:%i:%S')".format("'%s'" % t if t else "NULL")


str_to_mysql_datetime = StrToMysqlDatetime


# 字符转sqlServer时间
def StrToSqlServerDatetime(t = ""):
    return "CONVERT(DATETIME,{},120)".format("'%s'" % t if t else "NULL")


str_to_sqlserver_datetime = StrToSqlServerDatetime


# 字符转Oracle时间
def StrToOracleDatetime(t = ""):
    return "TO_DATE({},'yyyy-mm-dd hh24:mi:ss')".format("'%s'" % t if t else "NULL")


str_to_oracle_datetime = StrToOracleDatetime


# Oracle UTc
def OracleUtc():
    return "CEIL((SYSDATE-TO_DATE('1970-01-01','yyyy-mm-dd')-8/24-1)*86400)"


# Mysql UTc
def MysqlUtc():
    return "UNIX_TIMESTAMP()"


# SQL UTC
def SqlServerUtc(t = None):
    return "DATEDIFF(S,'1970-01-01 00:00:00', {})-8*3600".format("GETDATE()" if not t else "'%s'" % t)


# SQL UTC转时间
def SqlServerUtcToDate(t):
    return "DATEADD(S,{} + 8 * 3600,'1970-01-01 00:00:00')".format(t)


if __name__ == '__main__':
    a = UtcToDatetime('1111')
    print(a, dir(a))
    print(1111222, FormatStr(1111), UtcToStr('111'), GetUtc(), GetDatetime(), GetDatetimeStr())

    print(111, StrToMysqlDatetime('2019-11-28'))
    print(1111, StrToSqlServerDatetime('2019-11-28'))

    print(222, OracleUtc())
    print(111111111111, NumberToDateTimeStr('20171110121100'))
    print(222233, DatetimeStrToNumber(GetDatetimeStr()))
    xx = GetDatetime()
    print(xx.year + 100)
    print(dir(xx), xx, time.localtime())